﻿using System;
using System.Reflection;
using Common;
using Common.DataModels;
using Extensions.EventBus;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;

namespace Extensions.Services;

public static class AddRabbitMQ
{
    public static IServiceCollection AddRabbitMQSetup(this IServiceCollection services, SetupTypesConfig? config=null)
    {
        ArgumentNullException.ThrowIfNull(services);
        var enable = Appsettings.app("RabbitMQ", "Enable").ToBool();
        if (!enable)
        {
            return services;
        }

        var hostName = Appsettings.app("RabbitMQ", "HostName");
        var exchangeName = Appsettings.app("RabbitMQ", "ExchangeName");
        var port = Appsettings.app("RabbitMQ", "Port").ToInt32();
        var userName = Appsettings.app("RabbitMQ", "UserName");
        var pwd = Appsettings.app("RabbitMQ", "Password");
        var virtualHost = Appsettings.app("RabbitMQ", "VirtualHost");
        var queue = Appsettings.app("RabbitMQ", "Queue");

        services.Configure<IntegrationEventRabbitMQOptions>(options =>
        {
            options.HostName = hostName;
            options.ExchangeName = exchangeName;
            options.Port = port;
            options.UserName = userName;
            options.Password = pwd;
            options.VirtualHost = virtualHost;
        });
        if (!string.IsNullOrWhiteSpace(queue))
        {
            services.AddEventBus(queue,config?.EventBusAssembly??Array.Empty<Assembly>());
        }
        
        return services;
    }

    public static IApplicationBuilder UseRabbitMQSetup(this IApplicationBuilder app)
    {
        if (app == null) throw new ArgumentNullException(nameof(app));
        var enable = Appsettings.app("RabbitMQ", "Enable").ToBool();
        if (enable)
        {
            app.UseEventBusSetup();
        }
        return app;
    }
}